package com.jeecg.modules.jmreport.test;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
@Slf4j
@Service
public class AuthVerificationService {

    /**
     * 验证用户IP和授信码
     */
    public boolean verifyAppUser(HttpServletRequest request,String companyId, String inputAuthCode) {
        // 1. 获取用户真实IP
        String userIp = IpUtils.getRealClientIp(request);
        System.out.println("获取到用户IP: " + userIp);

        // 2. 检查输入的授信码是否为空
        if (inputAuthCode == null || inputAuthCode.trim().isEmpty()) {
            System.out.println("授信码为空");
            return false;
        }

        // 3. 到数据库验证IP和授信码是否匹配
        boolean isValid = DBUtil.verifyAppAuthCode(companyId,inputAuthCode); //DBUtil.verifyUserAuthCode(userIp, inputAuthCode);
        // 3. 如果验证通过，保存IP和公司ID到user_auth表（不存在则插入）
        if (isValid) {
            DBUtil.saveOrUpdateUserAuth(companyId, userIp, inputAuthCode);
            DBUtil.saveOrUpdateCompanyIp(companyId,userIp);
            // 添加到目标服务器防火墙白名单
            addIpToRemoteFirewall(userIp);
        }

        if (isValid) {
            System.out.println("用户验证成功: IP=" + userIp);
        } else {
            System.out.println("用户验证失败: IP=" + userIp);
        }

        return isValid;
    }

    /**
     * 验证用户IP和授信码
     */
    public boolean verifyUser(HttpServletRequest request,String companyId, String inputAuthCode,String remoteUserIP) {
        // 1. 获取用户真实IP
        String userIp = IpUtils.getRealClientIp(request);
        System.out.println("获取到用户IP: " + userIp);
        log.info("remote user ip : " + remoteUserIP);
        if (remoteUserIP!=null && remoteUserIP!="") {
            userIp = remoteUserIP;
        }

        // 2. 检查输入的授信码是否为空
        if (inputAuthCode == null || inputAuthCode.trim().isEmpty()) {
            System.out.println("授信码为空");
            return false;
        }

        // 3. 到数据库验证IP和授信码是否匹配
        boolean isValid = DBUtil.verifyAuthCode(companyId,inputAuthCode); //DBUtil.verifyUserAuthCode(userIp, inputAuthCode);
        // 3. 如果验证通过，保存IP和公司ID到user_auth表（不存在则插入）
        if (isValid) {
            DBUtil.saveOrUpdateUserAuth(companyId, userIp, inputAuthCode);
            DBUtil.saveOrUpdateCompanyIp(companyId,userIp);
            // 添加到目标服务器防火墙白名单
            addIpToRemoteFirewall(userIp);
        }

        if (isValid) {
            System.out.println("用户验证成功: IP=" + userIp);
        } else {
            System.out.println("用户验证失败: IP=" + userIp);
        }

        return isValid;
    }

    /**
     * 将IP地址添加到远程服务器的防火墙白名单
     */
    private void addIpToRemoteFirewall(String ipAddress) {
        try {
            // 从配置文件加载远程服务器信息
            Properties config = loadConfig();

            String remoteHost = config.getProperty("remote.server.host");
            String remoteUser = config.getProperty("remote.server.user");
            String remotePassword ="SUZIinfor@123"; //config.getProperty("remote.server.password");
            int remotePort = Integer.parseInt(config.getProperty("remote.server.port", "22"));

            // 使用JSch库建立SSH连接
            JSch jsch = new JSch();
            Session session = jsch.getSession(remoteUser, remoteHost, remotePort);
            session.setPassword(remotePassword);

            // 设置会话配置
            java.util.Properties sshConfig = new java.util.Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            session.setConfig(sshConfig);

            // 连接到远程服务器
            session.connect();
//            String command = "firewall-cmd --permanent --zone=whitelist  --add-source=" + ipAddress + "/32 && firewall-cmd --reload";

            // 执行防火墙添加白名单命令（这里以CentOS/RHEL为例）
            String command = "firewall-cmd --permanent --zone=whitelist  --add-source=" + ipAddress + " && firewall-cmd --reload";
            ChannelExec channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);

            // 获取命令执行结果
            BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
            channel.connect();

            // 读取输出日志
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }

            // 等待命令执行完成
            channel.disconnect();
            session.disconnect();

            System.out.println("Firewall update result: " + output.toString());

        } catch (Exception e) {
            // 记录错误日志
            System.err.println("Failed to add IP to remote firewall: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 加载配置文件
     */
    private Properties loadConfig() {
        Properties props = new Properties();
        try {
            props.load(getClass().getClassLoader().getResourceAsStream("firewall-config.properties"));
        } catch (Exception e) {
            System.err.println("Failed to load firewall config: " + e.getMessage());
        }
        return props;
    }

    /**
     * 生成MD5加密的授信码
     */
    public String generateAuthCode(String rawCode) {
        return MD5Utils.md5(rawCode);
    }

    /**
     * 验证原始码与MD5授信码是否匹配
     */
    public boolean verifyRawAuthCode(String rawCode, String md5AuthCode) {
        return MD5Utils.verify(rawCode, md5AuthCode);
    }
}